# Python 3 简单HTTP服务器
 
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
import socket
import urllib.parse
import pymysql
import json

class Http:
    def __init__(self) -> None:
        self.port = 0
        pass
    pass
class Mysql:
    def __init__(self) -> None:
        self.host = ""
        self.user = ""
        self.passwd = ""
        self.db = ""
        pass

class ConfigModel:
    def __init__(self) -> None:
        self.http:Http = None
        self.mysql:Mysql = None
        pass

def load_config()->ConfigModel:
    configModel = ConfigModel()
    with open("config.json",'r', encoding='utf-8') as file:
        content = file.read()
        dic = json.loads(content)
        http = Http()
        http.port = dic["http"]["port"]
        configModel.http = http

        mysql = Mysql()
        
        mysql_obj = dic["mysql"]
        if mysql_obj != None:
            mysql.host = mysql_obj["host"]
            mysql.user = mysql_obj["user"]
            mysql.passwd = mysql_obj["passwd"]
            mysql.db = mysql_obj["db"]
        configModel.mysql = mysql

        return configModel
    
    return configModel

class CustomSimpleHTTPRequestHandler(SimpleHTTPRequestHandler):

    def get_connection(self)->pymysql.Connect:
        config = load_config()
        return pymysql.connect(host=config.mysql.host, user=config.mysql.user, passwd=config.mysql.passwd, db=config.mysql.db)

    def end_headers(self) -> None:
        self.send_header('Access-Control-Allow-Origin', '*')
        return super().end_headers()
    
    def do_OPTIONS(self):
        print("do_OPTIONS")
        # 允许跨域请求的源，'*' 表示允许任何源
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        # 允许的方法
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        # 允许的头
        self.send_header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token')
        # 预检请求的有效时间
        self.send_header('Access-Control-Max-Age', '3600')
        self.send_header('Content-type', 'text/plain')
        self.end_headers()


    def do_GET(self) -> None:
        path = self.path
        parsed_path = urllib.parse.urlparse(path)
        pure_path = parsed_path.path
        print("do_GET ", pure_path)
        if pure_path == "/api/list":
            self.api_list()
        elif pure_path == "/api/list/get":
            self.api_list_get()
        elif pure_path == "/api/baseurl":
            self.api_base_url()
        else:
            self.api_from_db()
    
    def do_POST(self)-> None:
        path = self.path
        parsed_path = urllib.parse.urlparse(path)
        pure_path = parsed_path.path
        print("do_POST ", pure_path)
        if pure_path == "/api/list/modify":
            self.api_list_modify()
        elif pure_path == "/api/list/add":
            self.api_list_add()
        elif pure_path == "/api/list/delete":
            self.api_list_delete()
        else:
            self.api_from_db()
    
    def api_base_url(self):
        ret_data = {}
        ret_data["code"] = 200
        config = load_config()
        ret_data["data"] = "http://{}:{}".format(get_current_ip(), config.http.port)
        self.return_json(ret_data)

    def api_from_db(self):
        data = None
        ret_data = {}
        ret_data["code"] = 200
        path = self.path
        parsed_path = urllib.parse.urlparse(path)
        pure_path = parsed_path.path
        connection = self.get_connection()

        try:
            with connection.cursor() as cursor:
                cursor.execute("SELECT content FROM api WHERE api like '{}'".format(pure_path))  
                print("SELECT content FROM api WHERE api like '{}'".format(pure_path))  
                                    
                for r in cursor:
                    data = r[0]
            if data == None:
                print("data == None")  
                ret_data["code"] = 400
                ret_data["msg"] = "该路径 {} 不存在".format(pure_path)
            else:
                print("json.loads(data)")  
                ret_data = json.loads(data)
            self.return_json(ret_data)
        except Exception as e:
            ret_data["msg"] = "{}".format(e)
            ret_data["code"] = 400
            self.return_json(ret_data)
        finally:
            print("finally")
            connection.close()

        


    def api_list_modify(self):
        ret_data = {}
        ret_data["code"] = 200
        # 读取请求体中的JSON数据
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        dic_data = json.loads(body)
        id = dic_data["id"]
        api = dic_data["api"]
        content = dic_data["content"]
        remark = dic_data["remark"]

        result = None
        connection = self.get_connection()
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM api WHERE id={}".format(id))
            result = cursor.fetchone()
        
        if result:
            try:
                with connection.cursor() as cursor:
                    cursor.execute("UPDATE api SET api='{}', content='{}', remark='{}' WHERE id={}".format(api, content, remark, id))    
                    connection.commit()                     
            except Exception as e:
                ret_data["code"] = 500
                ret_data["msg"] = "{}".format(e)    
                self.return_json(ret_data)
                return
            finally:
                connection.close()
        else:
            ret_data["code"] = 500
            ret_data["msg"] = "该记录不存在"    
            self.return_json(ret_data)
            return 
            
        ret_data["msg"] = "更新成功"
        self.return_json(ret_data)
        return
    
    def api_list_add(self):
        ret_data = {}
        ret_data["code"] = 200
        # 读取请求体中的JSON数据
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        dic_data = json.loads(body)
        api = dic_data["api"]
        content = dic_data["content"]
        remark = dic_data["remark"]
        connection = self.get_connection()
        try:
            with connection.cursor() as cursor:
                cursor.execute("INSERT into api (api,content,remark) values('{}','{}','{}')".format(api, content, remark))
                connection.commit()
                # 获取影响的行数
                affected_rows = cursor.rowcount
                # 提交事务
        except Exception as e:
            connection.rollback()
            ret_data["code"] = 500
            ret_data["msg"] = "{}".format(e)    
            self.return_json(ret_data)
            return 
        finally:
            connection.close
            

        ret_data["code"] = 200
        ret_data["msg"] = "添加成功"    
        self.return_json(ret_data)
        return
    
    def api_list_get(self):
        # 获取请求的完整路径
        path = self.path
        # 解析GET参数
        parsed_path = urllib.parse.urlparse(path)
        print("parsed_path:", parsed_path)
        query_params = urllib.parse.parse_qs(parsed_path.query)
        print("query_params:", query_params)
         # 现在你可以通过query_params字典访问GET参数了
        # 例如，获取名为'param1'的参数
        id = query_params.get('id', [None])[0]
        data = {}
        ret_data = {}
        ret_data["code"] = 200

        connection = self.get_connection()
        with connection.cursor() as cursor:
            cursor.execute("SELECT id,api,content,remark FROM api WHERE id={}".format(id))
            for r in cursor:
                data["id"] = r[0]
                data["api"] = r[1]
                data["content"] = r[2]
                data["remark"] = r[3]

        ret_data["data"] = data
        self.return_json(ret_data)

    def api_list(self):
        data = {}
        apilist = []
        ret_data = {}
        ret_data["code"] = 200
        conn = self.get_connection()
        cur = conn.cursor()
        cur.execute("SELECT id,api,content,remark FROM api")
        for r in cur:
            item = {}
            item["id"] = r[0]
            item["api"] = r[1]
            item["content"] = r[2]
            item["remark"] = r[3]
            apilist.append(item)
        cur.close()
        conn.close()

        data["api_list"] = apilist
        ret_data["data"] = data
        
        self.return_json(ret_data)

    def api_list_delete(self):
        ret_data = {}
        ret_data["code"] = 200

        # 读取请求体中的JSON数据
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        dic_data = json.loads(body)
        id = dic_data["id"]
        result = None
        affected_rows = 0
        connection = self.get_connection()
        try:
            with connection.cursor() as cursor:
                cursor.execute("DELETE FROM api WHERE id={}".format(id))
                connection.commit()
                # 获取影响的行数
                affected_rows = cursor.rowcount
                # 提交事务
        except Exception as e:
            connection.rollback()
            ret_data["code"] = 500
            ret_data["msg"] = "{}".format(e)    
            self.return_json(ret_data)
            return
        finally:
            connection.close

        if affected_rows <= 0:
            ret_data["code"] = 400
            ret_data["msg"] = "数据不存在"    
            self.return_json(ret_data)
            return
        else:
            ret_data["code"] = 200
            ret_data["msg"] = "删除成功"    
            self.return_json(ret_data)
            return 
    
    def return_json(self, obj):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()
        jsonstr = json.dumps(obj)
        self.wfile.write(bytearray(jsonstr, 'utf-8'))


def get_current_ip():
    # 获取本机主机名
    hostname = socket.gethostname()
    # 根据主机名获取本机IP地址
    ip_address = socket.gethostbyname(hostname)
    return ip_address

def run(server_class=HTTPServer, handler_class=CustomSimpleHTTPRequestHandler):
    config = load_config()
    localip = get_current_ip()
    server_address = (localip, config.http.port)  # 服务器监听在0.0.0.0的8000端口
    httpd = server_class(server_address, handler_class)
    print('HTTP server running on http://{}:{}'.format(server_address[0],server_address[1]))
    httpd.serve_forever()
 
if __name__ == '__main__':
    run()